<template>
    <v-autocomplete
        v-model="selected"
        :items="items"
        :search-input.sync="search"
        :item-text="itemText"
        :item-value="itemValue"
        :item-key="itemKey"
        :label="label"
        placeholder="请输入字符"
        :rules="rules"
        return-object
        clearable
        no-data-text="没有数据"
    ></v-autocomplete>
</template>

<script>
    import axios from "axios";

    export default {
        props: {
            label:  {
                type: String,
                default: "用户名/手机号"
            },
            value:  {
                type: Object,
                default: null
            },
            rules: {
                type: Array,
                default: () => [],
            },
            itemText: {
                type: String,
                default: 'name',
            },
            itemValue: {
                type: String,
                default: 'id',
            },
            itemKey: {
                type: String,
                default: 'id',
            }
        },
        data: () => ({
            search: null,
            selected: null,
            items: [],
            inited: false,
            debounce: null
        }),
        watch: {
            selected(v) {
                this.$emit('input', v);
            },
            value(v) {
                if (!v)  {
                    this.selected = null;
                    return;
                }

                const key = this.itemKey;
                const id = v[key];

                if (!id) return;

                const idx = this.items.findIndex(el => el[key] == id);

                if( idx < 0) {
                    this.items.unshift(v);
                    this.selected = this.items[0];
                } else {
                    this.selected = this.items[idx];
                }
            },
            search (val) {
                if (this.selected && val === this.selected[this.itemText]) return;

                if ((val === null || val.length == 0) && this.inited) return;

                clearTimeout(this.debounce);
                this.debounce = setTimeout(() => {
                    axios.get(`/search/user`, {params: {  k: val } }).then((response) => {
                        this.items = response.data.data;
                        console.log('搜索',this.items)
                    })
                    .catch(function () {})
                    .then(function () {});
                }, 300);
            },
        },
        created() {
            if (this.value) {
                this.items.unshift(this.value);
                this.selected = this.items[0];
            } else {
                 axios.get(`/search/user`).then((response) => {
                    this.items = response.data.data;
                    this.inited = true;
                })
            }
        }
    }
</script>
